# coding=utf-8
import os
from function_utils import Global, Human, Common, PsUtil, TableRender


def get_release():
    name, ver = '', ''
    if os.path.isfile('/etc/os-release'):
        with open('/etc/os-release', 'r') as f:
            for line in f.readlines():
                if line.startswith('NAME='):
                    name = line.split('"')[1]
                elif line.startswith('VERSION='):
                    ver = line.split('"')[1]
    else:
        cmd = 'cat $(ls /etc/*-release| grep -v lsb-release| head -1) | head -1'
        name = Common.execute_cmd(cmd)[1]
    return name, ver


def get_network():
    cmd = '''ip a | grep -w inet | awk '{print $2" "$NF}' | awk -F: '{print $1}' '''
    nets = Common.execute_cmd(cmd)[1]
    devs = {}
    max_c = 0
    for line in nets.strip().split('\n'):
        ip, dev = line.split()
        if dev in devs:
            devs[dev].append(ip)
        else:
            devs[dev] = [ip]
        max_c = max(len(devs[dev]), max_c)

    info = ['']
    for dev, ips in devs.items():
        info[0] = '%s|%s' % (info[0], dev)
        info[0] = info[0].strip('|')
        ip_len = len(ips)
        for i in range(max_c):
            if len(info) - 1 < max_c:
                info.append('-')
            ip = ips[i] if i < ip_len else ''
            info[i + 1] = '%s|%s' % (info[i + 1], ip)
            info[i + 1] = info[i + 1].replace('-|', '')

    info = TableRender('\n'.join(info))
    return '\n'.join(map(lambda x: '**: %s**' % x, info.strip().split('\n')))


def get_disk():
    cmd = '''
    export LC_ALL=C
    fdisk -l 2>/dev/null| grep 'Disk /dev/'| awk '{print $2" "$3$4}'| sed 's/://g'| sed 's/,//g'
    unset LC_ALL
    '''
    disk = Common.execute_cmd(cmd)[1]
    _disks = []
    info = 'Disk|Size'
    for line in disk.strip().split('\n'):
        dev, size = line.split()
        info = '%s\n%s|%s' % (info, dev, size)
    info = TableRender(info)
    return '\n'.join(map(lambda x: '**: %s**' % x, info.strip().split('\n')))


def system_info():
    uname = os.uname()
    PsUtil.init()
    cpus = PsUtil.cpu_info()
    memory = PsUtil.memory()
    name, version = get_release()

    value = '''
<BLUE> ## > Release:
##### : {0} {1}

<BLUE> ## > OS:
##### : {2}-{3} ({4})

<BLUE> ## > CPU:
##### : {5} ({6} Cores {7}MHz)

<BLUE> ## > Memory:
##### : {8} (Swap: {9})

<BLUE> ## > Disk:
{10}

<BLUE> ## > Network:
{11}

<BLUE> ## > Boot:
##### : {12}
    '''.format(
        name, version,
        uname[0], uname[2], uname[1],
        '|'.join(set(cpus[0])).strip(), len(cpus[0]), '|'.join(set(cpus[1])),
        Human.size(memory['total']), Human.size(memory['swap_total']),
        get_disk(),
        get_network(),
        Human.time(PsUtil.BOOT_TIME)
    )

    return value


def write_widgets_value(value):
    data = [
        {"MultiInfoText": value}
    ]
    Global.values_write(data)
    Global.report_info(100)


def main():
    write_widgets_value(system_info())


if __name__ == '__main__':
    main()
